package org.csu.mypetstore.controller;

import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Param;
import org.csu.mypetstore.common.CommonResponse;
import org.csu.mypetstore.common.ResponseCode;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;
import java.util.PrimitiveIterator;


@RestController
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private CartService cartService;


    // 用户登录
    @PostMapping("/signOn")
    public CommonResponse<Object> signOn(@Validated @RequestBody SignOn user,
                                         HttpSession session,
                                         Model model,
                                         BindingResult bindingResult) {
        StringBuilder errorMessage = new StringBuilder();
        if (bindingResult.hasErrors()) {
            for (ObjectError objectError : bindingResult.getAllErrors()) {
                errorMessage.append(objectError.getDefaultMessage());
                errorMessage.append(", ");
            }
            return CommonResponse.createForError((String) model.getAttribute("errorMessage"));
        } else {
            SignOn signOn = (SignOn) accountService.login(user).getData();
            if (signOn == null) {
                return CommonResponse.createForError((String) model.getAttribute("errorMessage"));
            } else {
                Account account = (Account) accountService.getAccountBySignOn(signOn).getData();
                session.setAttribute("account", account);
                // 查询成功，无论是否为空
                List<Cart> cartList = cartService.getCartListByUserId(account.getUserId()).getData();
                session.setAttribute("cartList", cartList);

                BigDecimal subTotal = BigDecimal.valueOf(0);
                if (cartList != null) {
                    for (Cart cart : cartList) {
                        subTotal = subTotal.add(cartService.getTotalCost(cart));
                    }
                }
                session.setAttribute("subTotal", subTotal);
                String message = "登录成功";
                return CommonResponse.createForSuccess(message, new AccountVO(account, subTotal, cartList));
            }
        }
    }

    // 用户注册
    @PostMapping("/register")
    public CommonResponse<Object> register(@RequestParam("username") String username,
                                           @RequestParam("password") String password) {
        return accountService.register(username, password);
    }

    // 用户完善信息
    @PostMapping("/account/info")
    public CommonResponse<Object> improveInfo(@RequestBody Account account) {
        return accountService.improveInfo(account);
    }

    @PostMapping("/account/password")
    public CommonResponse<Object> changePassword(@RequestParam("old_password") String old_password,
                                                 @RequestParam("new_password") String new_password,
                                                 HttpSession session) {
        Account account = (Account) session.getAttribute("account");
        return accountService.changePassword(account.getAccountId(), old_password, new_password);
    }


}
